/**
 * Copyright (C) 2015~2050 by foolstudio. All rights reserved.
 *
 * 本源文件中代码不经允许，不得用于商业用途，作者保留所有权。
 *
 * 作者：汪永松
 *
 * 电子邮箱：foolstudio@qq.com
 *
 */
package com.foolstudio.VehicleNumDemo.activities;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.foolstudio.util.FooSysUtil;
import com.foolstudio.VehicleNumDemo.IDef;
import com.foolstudio.VehicleNumDemo.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class CaptureActivity extends Activity implements OnClickListener,
		Callback, PictureCallback, AutoFocusCallback {

	public static int Desired_Preview_Width = 1280;
	public static int Desired_Preview_Height = 720;
	public static int Desired_Picture_Width = 1280;
	public static int Desired_Picture_Height = 960;

	private SurfaceView mVideoView = null;
	private SurfaceHolder mHolder = null;
	private Camera mCamera = null;
	//
	private ImageButton mBtnCapture = null;

	//超时计时
	private Timer mTimer = null;
	private Handler mMsgHandler = null;
	private int mCounter = 0;

	//对焦超时为6秒
	private static final int Timeout = 6;

	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		//获取按钮控件并设置点击侦听
		mBtnCapture = (ImageButton)findViewById(R.id.btn_capture);
		mBtnCapture.setOnClickListener(this);

		//获取视频渲染视图
		this.mVideoView = (SurfaceView)findViewById(R.id.preview_view);
		this.mHolder = this.mVideoView.getHolder();
		this.mHolder.addCallback(this);
		//this.mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		//初始化主线程消息队列处理器接口
		mMsgHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == IDef.Msg_Tick) {
					mCounter++;
					if(mCounter >= Timeout) {
						timerTimeout();
					}
				}
			}
		};
	}

	@Override
	protected void onDestroy() {

		//取消超时计时
		stopTimer();

		//停止预览，释放资源
		if(this.mCamera != null) {
			this.mCamera.stopPreview();
			this.mCamera.release();
			this.mCamera = null;
		}

		// TODO Auto-generated method stub
		super.onDestroy();
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		//初始化照相机
		openCamera();
		startPreview();
	}

	private void openCamera() {
		try { //确认照相机处于关闭状态
			closeCamera();
			//打开照相机
			this.mCamera = Camera.open();
			//获取参数，设置参数
			Camera.Parameters params = this.mCamera.getParameters();

			//获取所支持的大小 @2015-06-30 兼容性解决方案
			getSupportedPreviewSize(params);
			getSupportedPictureSize(params);

			params.setPictureFormat(ImageFormat.JPEG);
			params.setPreviewSize(Desired_Preview_Width, Desired_Preview_Height);
			//设置场景
			//params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
			//params.setSceneMode(Camera.Parameters.SCENE_MODE_FIREWORKS);
			//params.setFocusMode(Parameters.FOCUS_MODE_AUTO);
			params.setPictureSize(Desired_Picture_Width, Desired_Picture_Height);

			//@2015-06-30 兼容性解决方案
			if (Build.VERSION.SDK_INT >= 8) {
				this.mCamera.setDisplayOrientation(90);
			} else {
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
					params.set("orientation", "portrait");
					params.set("rotation", 90);
				} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					params.set("orientation", "landscape");
					params.set("rotation", 90);
				}
			}

			//设置白平衡
			//params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_FLUORESCENT);

			this.mCamera.setParameters(params);
			this.mCamera.setPreviewDisplay(mHolder);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//获取支持的预览大小
	private void getSupportedPreviewSize(Parameters params) {

		List<Size> sizes = params.getSupportedPreviewSizes();
		Comparator<Size> comparator = new Comparator<Size> () {

			@Override
			public int compare(Size arg1, Size arg2) {

				//倒序
				if(arg2.width > arg1.width) {
					return (1);
				} else if(arg2.width == arg1.width) {
					if(arg2.height > arg1.height) {
						return (1);
					} else if (arg2.height == arg1.height) {
						return (0);
					} else {
						return (-1);
					}
				} else {
					return (-1);
				}
			}

		};
		Collections.sort(sizes, comparator);

		StringBuffer sb  = new StringBuffer();
		boolean isGot = false;
		for(int i = 0; i < sizes.size(); ++i) {

			Size tSize = sizes.get(i);

			sb.append("(");
			sb.append(tSize.width);
			sb.append(",");
			sb.append(tSize.height);
			sb.append(") ");

			if( (tSize.width == Desired_Preview_Width) && !isGot) { //1280x
				Desired_Preview_Height = tSize.height;
				isGot = true;
			};
		}
		if(isGot == false) { //没有匹配上
			Size tSize = sizes.get(sizes.size()/2);
			Desired_Preview_Width = tSize.width;
			Desired_Preview_Height = tSize.height;
		}

		Logger.getLogger(IDef.App_Tag).info("SupportedPreviewSizes="+sb.toString() );
	}

	//获取支持的图片大小
	private void getSupportedPictureSize(Parameters params) {

		List<Size> sizes = params.getSupportedPictureSizes();
		Comparator<Size> comparator = new Comparator<Size> () {

			@Override
			public int compare(Size arg1, Size arg2) {

				//倒序
				if(arg2.width > arg1.width) {
					return (1);
				} else if(arg2.width == arg1.width) {
					if(arg2.height > arg1.height) {
						return (1);
					} else if (arg2.height == arg1.height) {
						return (0);
					} else {
						return (-1);
					}
				} else {
					return (-1);
				}
			}

		};
		Collections.sort(sizes, comparator);

		StringBuffer sb  = new StringBuffer();
		boolean isGot = false;
		for(int i = 0; i < sizes.size(); ++i) {

			Size tSize = sizes.get(i);

			sb.append("(");
			sb.append(tSize.width);
			sb.append(",");
			sb.append(tSize.height);
			sb.append(") ");

			if((tSize.width == Desired_Picture_Width) && !isGot) { //1280x
				Desired_Picture_Height = tSize.height;
				isGot = true;
			}
		}
		if(isGot == false) { //没有匹配上
			Size tSize = sizes.get(sizes.size()/2);
			Desired_Picture_Width = tSize.width;
			Desired_Picture_Height = tSize.height;
		}

		Logger.getLogger(IDef.App_Tag).info("SupportedPictureSizes="+sb.toString() );
	}

	private void closeCamera() {
		if (this.mCamera == null) {
			return;
		}
		try { // 使照相机重新获取资源的控制
			this.mCamera.reconnect();
			// 停止预览，释放资源
			this.mCamera.stopPreview();
			this.mCamera.release();
			this.mCamera = null;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	private void startPreview() {
		// 先使照相机处于停止预览状态
		this.mCamera.stopPreview();
		// 开始预览
		this.mCamera.startPreview();
	}

	@Override
	public void onAutoFocus(boolean success, Camera camera) {

		if(success) {

			//停止聚焦超时计时器
			stopTimer();

			Logger.getLogger(IDef.App_Tag).log(Level.FINE, "Camera autofocus OK");

			//startPreview();
			camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
			//camera.autoFocus(null);
			camera.takePicture(null, null, this);
		}
	}

	@Override
	public void onClick(View v) {
		if(this.mCamera != null) {

			//startPreview();
			this.mCamera.autoFocus(this);

			//隐藏按钮
			mBtnCapture.setVisibility(View.INVISIBLE);

			//启动超时计时器
			startTimer();
		}
	}

	//自动对焦超时计时器开始计时
	private void startTimer() {
		this.mTimer = new Timer();
		this.mCounter = 0;

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				mMsgHandler.sendEmptyMessage(IDef.Msg_Tick);
			}
		};
		//规划任务执行的时点和频率
		this.mTimer.scheduleAtFixedRate(task, 0, 1000L);
	}

	//停止聚焦超时计时器
	private void stopTimer() {
		//取消超时计时
		if(this.mTimer != null) {
			this.mTimer.cancel();
			this.mTimer.purge();
			this.mTimer = null;
		}
	}

	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
		final String filePath = IDef.App_Dir+File.separatorChar+
				FooSysUtil.getInstance().getTimeStr("")+".jpg";
		File f = new File(filePath);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
			//拍完照之后会停止预览，需要恢复预览
			//startPreview();
			returnResult(filePath);
		} catch (Exception e) { e.printStackTrace(); }
	}

	private void returnResult(String filePath) {

		Intent resultIntent = new Intent();
		resultIntent.putExtra(IDef.Extra_File_Path, filePath);
		this.setResult(RESULT_OK, resultIntent);
		this.finishActivity(IDef.Req_Code_Camera);
		this.finish();
	}

	//自动对焦超时
	protected void timerTimeout() {

		//停止聚焦超时计时器
		stopTimer();

		Logger.getLogger(IDef.App_Tag).log(Level.WARNING, "Camera autofocus timeout");

		if(this.mCamera != null) {
			this.mCamera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
			//camera.autoFocus(null);
			this.mCamera.takePicture(null, null, this);
		}
	}
};
